package org.exam.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.exam.system.domain.Employee;
import org.exam.system.domain.Role;
import org.exam.system.mapper.RoleMapper;
import org.exam.system.query.RoleQuery;
import org.exam.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    @Transactional
    public void add(Role role) {
        roleMapper.add(role);

        List<Long> permission = role.getPermission();
        List<Long> menus = role.getMenus();
        if (permission.size() > 0) {
            roleMapper.addRolePermission(role);
        }
        if (menus.size() > 0) {
            roleMapper.addRoleMenu(role);
        }

    }

    @Override
    @Transactional
    public void delete(Long id) {
        roleMapper.delete(id);
        roleMapper.deletePermissionByRoleId(id);
        roleMapper.deleteMenuByRoleId(id);

        //条件删除
    }

    @Override
    public Role get(Long id) {
        return roleMapper.get(id);
    }

    @Override
    public List<Role> getAll() {
        return roleMapper.getAll();
    }

    @Override
    @Transactional
    public void update(Role role) {
        roleMapper.update(role);
        roleMapper.deletePermissionByRoleId(role.getId());
        roleMapper.deleteMenuByRoleId(role.getId());
        List<Long> permission = role.getPermission();
        List<Long> menus = role.getMenus();
        if (permission.size() > 0) {
            roleMapper.addRolePermission(role);
        }
        if (menus.size() > 0) {
            roleMapper.addRoleMenu(role);
        }

    }

    @Override
    public void patchDelete(Long[] ids) {
        roleMapper.patchDelete(ids);
        for (Long id : ids) {
            delete(id);
        }
    }

    @Override
    public PageInfo<Role> queryPage(RoleQuery roleQuery) {
        PageHelper.startPage(roleQuery.getCurrentPage(), roleQuery.getPageSize());
        List<Role> data = roleMapper.queryPage(roleQuery);
        for (Role datum : data) {
            List<Long> roles = roleMapper.findRoleByEmployeeId(datum.getId());
            datum.setPermission(roles);
        }
        return new PageInfo<>(data);
    }


}
